package uk.ac.cam.cl.android.jwdb;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class ShakeListener implements SensorEventListener {
	private SensorManager sensorManager;
	private Sensor accelerometer;
	private static boolean hasHadShake = false;
	private double[] pastValues;  // Circular array
	private int pastValuesIndex = 0;
	private int numPastValues = 20;
	private static Action listener = null;
	
	public ShakeListener(Context context) {
	    initialisePastValues();
		sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
	    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
	}
	
	private void initialisePastValues() {
		pastValues = new double[numPastValues];
		
		for (int i = 0; i < numPastValues; i++) {
			pastValues[i] = 0.0;
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// ...
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		double x = event.values[0];
		pastValues[pastValuesIndex] = x;
		pastValuesIndex = (pastValuesIndex + 1) % numPastValues;
		if (pastValuesIndex % 10 == 0) {
			double deviation = StandardDeviation.StandardDeviationMean(pastValues);
			
			if (deviation > 10.0) {
				hasHadShake = true;
				Log.d("Sensor", "Shake");
				if (listener != null) listener.done();
			}
		}
	}
	
	public static boolean hasHadShake() {
		if (hasHadShake) {
			hasHadShake = false;
			return true;
		}
		else return false;
	}
	
	public static void registerListener(Action theListener) {
		listener = theListener;
	}
	
}
